//企业微信服务
module.exports = function (app, models, $, db, nm) {
    function Wecom(args){
        args = args || {}
        let corpid = args.corpid,
        messageAgentid = args.messageAgentid
        messageSecret = args.messageSecret
        checkinAgentid = args.checkinAgentid
        checkinSecret = args.checkinSecret
        let secrets = {}
        secrets[corpid] = args.secret
        secrets[messageAgentid] = messageSecret
        secrets[checkinAgentid] = checkinSecret

        let access_tokens = {}
        //获取token
        async function gettoken(agentid) {
            agentid = agentid || corpid
            let now = new Date().getTime()
            if (access_tokens[agentid] && now - access_tokens[agentid + '_time'] < access_tokens[agentid + '_expires_in'] - 1000 * 60) {
                return access_tokens[agentid]
            }
            let ret = await $.node.fetch(`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corpid}&corpsecret=${secrets[agentid]}`)
            if (ret.access_token) {
                access_tokens[agentid] = ret.access_token
                access_tokens[agentid + '_time'] = now
                access_tokens[agentid + '_expires_in'] = ret.expires_in * 1000
            }
            return access_tokens[agentid]
        }
        //获取ticket
        let tickets = {}
        async function get_jsapi_ticket(agentid) {
            let now = new Date().getTime()
            if (tickets[agentid] && now - tickets[agentid + '_time'] < tickets[agentid + '_expires_in'] - 1000 * 60) {
                return tickets[agentid]
            }
            let access_token = await gettoken(agentid)
            let ret = await $.node.fetch(`https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=${access_token}`)
            if (ret.ticket) {
                tickets[agentid] = ret.access_token
                tickets[agentid + '_time'] = now
                tickets[agentid + '_expires_in'] = ret.expires_in * 1000
            }
            return tickets[agentid]
        }
        //获取部门列表
        this.department_list = async function(){
            return await $.node.fetch(`https://qyapi.weixin.qq.com/cgi-bin/department/simplelist?access_token=${await gettoken()}`)
        }
        //获取成员ID列表
        this.user_list_id = async function() {
            return await $.node.fetch(`https://qyapi.weixin.qq.com/cgi-bin/user/list_id?access_token=${await gettoken()}`)
        }
        //发送消息
        this.message_send = async function(data){
            data.agentid = messageAgentid
            let token = await gettoken(messageAgentid)
            return await $.node.fetch({
                url: `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${token}`,
                data
            })
        }
        //获取打卡记录
        this.getcheckindata = async function(data){
            return await $.node.fetch({
                url: `https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token=${await gettoken(checkinAgentid)}`,
                data
            })
        }
        //获取打卡日报数据 
        this.getcheckin_daydata = async function(data){
            return await $.node.fetch({
                url:`https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckin_daydata?access_token=${await gettoken(checkinAgentid)}`,
                data
            })
        }
        //获取打卡月报数据 
        this.getcheckin_monthdata = async function(data){
            return await $.node.fetch({
                url:`https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckin_monthdata?access_token=${await gettoken(checkinAgentid)}`,
                data
            })
        }
        //获取应用在工作台展示的模版
        this.get_workbench_template = async function(agentid){
            agentid = agentid || messageAgentid
            return await $.node.fetch({
                url:`https://qyapi.weixin.qq.com/cgi-bin/agent/get_workbench_template?access_token=${await gettoken(messageAgentid)}`,
                data:{ agentid }
            })
        }
        //设置应用在工作台展示的模版
        this.set_workbench_template = async function(data){
            data.agentid = data.agentid || messageAgentid
            return await $.node.fetch({
                url:`https://qyapi.weixin.qq.com/cgi-bin/agent/set_workbench_template?access_token=${await gettoken(messageAgentid)}`,
                data
            })
        }
        //获取菜单
        this.menu_get = async function(agentid){
            agentid = agentid || messageAgentid
            return await $.node.fetch(`https://qyapi.weixin.qq.com/cgi-bin/menu/get?access_token=${await gettoken(agentid)}&agentid=${agentid}`)
        }
        //创建菜单
        this.menu_create = async function(data,agentid){
            data.agentid = data.agentid || messageAgentid
            return await $.node.fetch({
                url:`https://qyapi.weixin.qq.com/cgi-bin/menu/create?access_token=${await gettoken(agentid)}&agentid=${agentid}`,
                data
            })
        }
    }
    ///创建消息体
    async function buildMessage(args){
        args = args || {}
        let message = args
        if(args.text){
            message = $.merge({
                "msgtype" : "text",
                "text" : {
                    "content" : ''
                },
                "safe":0,
                "enable_id_trans": 0,
                "enable_duplicate_check": 0,
                "duplicate_check_interval": 1800
            },args)
        }else if(args.miniprogram_notice){
            message = $.merge({
                "msgtype" : "miniprogram_notice",
                "miniprogram_notice" : {
                     "appid": Config.tencent.appid,
                     "page": '',
                     "title": '',
                     "description": $.date().Format('MM月dd日 hh:mm'),
                     "emphasis_first_item": true,
                     "content_item": []
                 },
                "enable_id_trans": 0,
                "enable_duplicate_check": 0,
                "duplicate_check_interval": 1800
             },args)
        }else if(args.news){
            message = $.merge({
                "msgtype" : "news",
                "news" : {
                    "articles" : [
                        {
                            "title" : '',
                            "description" : '',
                            "url" : '',
                            "picurl" : "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png", 
                        }
                             ]
                },
                "enable_id_trans": 0,
                "enable_duplicate_check": 0,
                "duplicate_check_interval": 1800
             },args)
             for(let i = 0; i < message.news.articles.length; i ++){
                if(message.news.articles[i].pagepath) message.news.articles[i].appid = Config.tencent.appid
             }
        }
        return message
    }
    //按单位获取打卡记录数据
    async function getcheckindata(args){
        let unit = await models.unit.findSync({ unitId: args.unitId })
        let wecom = new Wecom(unit)
        let users = await models.user.listSync({unitId:unit.unitId,source:'wecom'})
        let useridlist = [],records = []
        for(let i = 0; i < users.length; i ++){
            if(i > 0 && (i % 100 == 0 || i == users.length - 1)){
                let record = await wecom.getcheckindata({
                    opencheckindatatype:args.opencheckindatatype || 3,
                    starttime:args.starttime,
                    endtime:args.endtime,
                    useridlist
                })
                useridlist = []
                if(record.checkindata) records = records.concat(record.checkindata)
            }else{
                useridlist.push(users[i].userName)
            }
        }
        return records
    }
    //按单位获取打卡日报数据
    async function getcheckinDaydata(args){
        let unit = await models.unit.findSync({ unitId: args.unitId })
        let wecom = new Wecom(unit)
        let users = await models.user.listSync({unitId:unit.unitId,source:'wecom'})
        let useridlist = [],records = []
        for(let i = 0; i < users.length; i ++){
            if(i > 0 && (i % 100 == 0 || i == users.length - 1)){
                let record = await wecom.getcheckin_daydata({
                    starttime:args.starttime,
                    endtime:args.endtime,
                    useridlist
                })
                if(record.datas) records = records.concat(record.datas)
            }else{
                useridlist.push(users[i].userName)
            }
        }
        return records
    }
    //按单位获取打卡月报数据
    async function getcheckinMonthdata(args){
        let unit = await models.unit.findSync({ unitId: args.unitId })
        let wecom = new Wecom(unit)
        let users = await models.user.listSync({unitId:unit.unitId,source:'wecom'})
        let useridlist = [],records = []
        for(let i = 0; i < users.length; i ++){
            if(i > 0 && (i % 100 == 0 || i == users.length - 1)){
                let record = await wecom.getcheckin_monthdata({
                    starttime:args.starttime,
                    endtime:args.endtime,
                    useridlist
                })
                if(record.datas) records = records.concat(record.datas)
            }else{
                useridlist.push(users[i].userName)
            }
        }
        return records
    }
    //获取应用在工作台展示的模版
    async function getWorkbenchTemplate(unitId){
        return new Wecom(await models.unit.findSync({ unitId })).get_workbench_template()
    }
    //设置应用在工作台展示的模版
    async function setWorkbenchTemplate(data){
        return new Wecom(await models.unit.findSync({ unitId:data.unitId })).set_workbench_template(data)
    }
    //获取菜单 
    async function menuGet(unitId){
        return new Wecom(await models.unit.findSync({ unitId })).menu_get()
    }
    //menu_create
    async function menuCreate(unitId,data){
        return new Wecom(await models.unit.findSync({ unitId })).menu_create(data)
    }
    return {
        getWorkbenchTemplate,
        setWorkbenchTemplate,
        getcheckindata,
        getcheckinDaydata,
        getcheckinMonthdata,
        menuGet,
        menuCreate
    }
}

// http://cqhuatang.com/SMSServer/smssend
// {
//     "appkey": "152312",
//     "appsecret": "FYWHI6",
//     "templateid": "1683344307882PlV",
//     "phone": "17729603616",
//     "extnum": "12345",
//     "templateparams": [
//         "1"
//     ]
// }